package com.itheima.cs.dao.dbd;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.itheima.cs.R;
import com.itheima.cs.entity.dbd.PrinterConfig;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

public class PrinterConfigActivity extends AppCompatActivity {
    private EditText etName, etIp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_printer_config);
        etName = findViewById(R.id.et_printer_name);
        etIp = findViewById(R.id.et_printer_ip);
        findViewById(R.id.btn_save).setOnClickListener(v -> savePrinter());
    }

    private void savePrinter() {
        String name = etName.getText().toString();
        String ip = etIp.getText().toString();

        if (name.isEmpty() || ip.isEmpty()) {
            Toast.makeText(this, "请填写完整信息", Toast.LENGTH_SHORT).show();
            return;
        }

        List<PrinterConfig> printers = loadPrinters();
        printers.add(new PrinterConfig(name, ip));
        savePrinters(printers);
        finish();
    }

    private List<PrinterConfig> loadPrinters() {
        SharedPreferences prefs = getSharedPreferences("printer_config", MODE_PRIVATE);
        String json = prefs.getString("printers", "[]");
        Type type = new TypeToken<ArrayList<PrinterConfig>>(){}.getType();
        return new Gson().fromJson(json, type);
    }

    private void savePrinters(List<PrinterConfig> printers) {
        SharedPreferences prefs = getSharedPreferences("printer_config", MODE_PRIVATE);
        prefs.edit().putString("printers", new Gson().toJson(printers)).apply();
    }
}
